package cn.micai.base.lambda;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/6/21 15:40
 */
public class NowJava8 {

    public static void main(String [] args) {

        List<Person> persons = Arrays.asList(
                new Person("mkyong", 30),
                new Person("jack", 20),
                new Person("lawrence", 40)
        );

        Person person = persons.stream()                        // Convert to steam
                .filter(x -> "jack".equals(x.getName()))        // we want "jack" only
                .findAny()                                      // If 'findAny' then return found
                .orElse(null);                           // If not found, return null

        System.out.println(person);

        Person person1 = persons.stream()
                .filter(x -> "ahmook".equals(x.getName()))
                .findAny()
                .orElse(null);

        System.out.println(person1);

        Person person2 = persons.stream()
                .filter((p) -> "jack".equals(p.getName()) && 20 == p.getAge())
                .findAny()
                .orElse(null);
        System.out.println(person2);

        // or like this
        Person person3 = persons.stream()
                .filter(p -> {
                    if ("jack".equals(p.getName()) && 20 == p.getAge()) {
                        return true;
                    }
                    return false;
                }).findAny()
                .orElse(null);
        System.out.println(person3);

        // Streams filter() and map()
        String name = persons.stream()
                .filter(x -> "jack".equals(x.getName()))
                .map(Person::getName)
                .findAny()
                .orElse("");
        System.out.println("name: " + name);

        List<String> collect = persons.stream()
                .map(Person::getName)
                .collect(Collectors.toList());
        collect.forEach(System.out::println);
    }
}
